<?php declare(strict_types=1);


namespace App\Http\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Exception\SwoftException;
use Swoft\Http\Message\Request;
use Swoft\Http\Server\Contract\MiddlewareInterface;
use Swoft\Context\Context;
use App\Http\Utils\Jwt;
/**
 * Class AuthMiddleware
 *
 * @Bean()
 */
class AuthMiddleware implements MiddlewareInterface
{
    /**
     * Process an incoming server request.
     *
     * @param ServerRequestInterface|Request $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     * @inheritdoc
     * @throws SwoftException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // before request handle
        // 判断token
        $Authorization = $request->getHeaderLine("Authorization");
        if ($Authorization == null)
        {
            $json = ['error'=>"-1",'errorMsg'=>'请键入Header(Authorization:Bearer {$token})'];
            $response = Context::mustGet()->getResponse();
            return $response->withStatus(400)->withData($json);
        }
        $tokens = explode(" ",$Authorization);
        if(count($tokens) != 2)
        {
            $json = ['error'=>"-2",'errorMsg'=>'Authorization格式不正确(Authorization:Bearer {$token})'];
            $response = Context::mustGet()->getResponse();
            return $response->withStatus(400)->withData($json);
        }
        list($bearer, $token) = $tokens;
        if ($bearer != "Bearer")
        {
            $json = ['error'=>"-2",'errorMsg'=>'Authorization格式不正确(Authorization:Bearer {$token})'];
            $response = Context::mustGet()->getResponse();
            return $response->withStatus(400)->withData($json);
        }
        $jwt = Jwt::verifyToken($token);
        if($jwt == -1)
        {
            $json = ['error'=>"-3",'errorMsg'=>'授权失败'];
            $response = Context::mustGet()->getResponse();
            return $response->withStatus(400)->withData($json);
        }
        if($jwt == -2)
        {
            $json = ['error'=>"-3",'errorMsg'=>'Token已过期'];
            $response = Context::mustGet()->getResponse();
            return $response->withStatus(400)->withData($json);
        }
        if($jwt == -3)
        {
            $json = ['error'=>"-3",'errorMsg'=>'用户已登出'];
            $response = Context::mustGet()->getResponse();
            return $response->withStatus(400)->withData($json);
        }
        if($jwt == -4)
        {
            $json = ['error'=>"-3",'errorMsg'=>'服务器错误'];
            $response = Context::mustGet()->getResponse();
            return $response->withStatus(400)->withData($json);
        }
        Context()->set("user",$jwt['aud']);
        return $handler->handle($request);
    }
}
